﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Webcam.Image
{
    public static class VectorMath
    {
        /// <summary>
        /// Get the minimum distance of a point to a line
        /// http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
        /// </summary>
        /// <param name="l"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static float DistancePointToLine(Line l, Point p)
        {
            Point l1 = l.p1;
            Point l2 = l.p2;

            float uTop = (p.X - l1.X)*(l2.X - l1.X) + (p.Y - l1.Y)*(l2.Y - l1.Y);
            float uBottom = LengthOfLineSquared(Point.Subtract(l2, l1));
            float u = uTop / uBottom;

            // nearest point on line
            float x = l1.X + u * (l2.X - l1.X);
            float y = l1.Y + u * (l2.Y - l1.Y);

            Point nearestPoint = new Point((int)x, (int)y);

            Point Difference = Point.Subtract(nearestPoint, p);
            return LengthOfLine(Difference);
        }



        /// <summary>
        /// Find the length of a point squared
        /// </summary>
        /// <param name="p1"></param>
        /// <returns></returns>
        public static float LengthOfLineSquared(Point p1)
        {
            float x = p1.X*p1.X + p1.Y*p1.Y;
            return x;
        }

        /// <summary>
        /// Find the length of a line
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static float LengthOfLine(Point p)
        {
            return (float)Math.Sqrt(LengthOfLineSquared(p));
        }

        /// <summary>
        /// Gets angle from horizontal
        /// </summary>
        /// <param name="grad">The gradient of the line</param>
        /// <returns>Angle in radians</returns>
        public static float aTan(float grad)
        {
            return (float)Math.Atan(grad);
        }


        public static bool OverlappingPairs(int x11, int x12, int x21, int x22)
        {
            int max = Math.Max(x11, Math.Max(x12, Math.Max(x21, x22)))+1;
            bool[] vals = new bool[max];

            int s = Math.Min(x11, x12);
            int e = Math.Max(x11, x12);

            for (int i = s; i <= e; i++)
            {
                vals[i] = true;
            }

            if (vals[x21] || vals[x22])
                return true;

            return false;
        }


    }
}
